import os
import re
import time
from samplebatch import Sample ,logger
import json
# 初始化翻译器
translator = Sample()

from logger import logger

class Translate:
    def __init__(self,id,secret,source = 'ko',target = 'zh'):
        os.environ["ALIBABA_CLOUD_ACCESS_KEY_ID"] =id  #"your id" 
        os.environ["ALIBABA_CLOUD_ACCESS_KEY_SECRET"]= secret  #"your secret"
        self.source_language = source
        self.target_language = target
        
    def translate_text(self, text):
        """
        使用自定义的Translate API翻译韩语文本到中文。
        """
        try:
            translated = translator.alitran_batch(text , 
                                                  source = self.source_language ,
                                                  target = self.target_language)
            return translated
        except Exception as e:
            logger.debug(f"翻译错误: {e}")
            exit(1)
            return text  # 如果翻译失败，则返回原文本


    def process_file(self , file_path):
        """
        处理文件，收集待翻译内容并进行集中翻译
        """
        new_content = []   
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.readlines()
        logger.debug(f"处理文件: {file_path}")
        strings_to_translate =  {}
        # positions = []  # 保存每个待翻译内容在文件中的位置
        index = 0
        # last = 0
        # 收集文件中的字符串常量和注释内容
        linenum = 0
        lastnum  = 0
        for i, line in enumerate(content):
            # 查找行中的字符串常量（无论位置）
            strings = re.findall(r'[\uac00-\ud7af]+(?:\s[\uac00-\ud7af]+)*', line)
            # if len(strings) == 0 :
            #     return
            linenum=i
            for s in strings:
                strings_to_translate[index] = s            
                # 记录位置和类型
                if index == 49  :
                    self.processing(strings_to_translate ,linenum ,file_path,lastnum ,new_content,content)
                    strings_to_translate = {}
                    index= 0
                    lastnum = i
                    continue
                index += 1
        if  len(strings_to_translate) > 0 :
            self.processing(strings_to_translate ,linenum ,file_path,lastnum ,new_content,content)
        
        with open(file_path, 'w', encoding='utf-8') as f:
            f.writelines(new_content)    # 将翻译后的内容写回文件

    def processing (self,strings_to_translate ,linenum ,file_path,lastnum,new_content ,content ) :
        
        logger.debug(f"需要翻译的内容: ")
        logger.debug(strings_to_translate)
        all_text_to_translate = json.dumps({str(key): value for key, value in strings_to_translate.items()})
        text_to_translate = all_text_to_translate
        # text_to_translate = "{" + text_to_translate + "}" 
        
        # 进行翻译
        translated_text = self.translate_text(text_to_translate)
        # logger.debug(f"结果: {translated_text}")
        # 分割翻译后的结果
        # translated_text = translated_text[1:-1]
        translated_parts = json.loads(translated_text)

        if len(translated_parts) != len(strings_to_translate):
            logger.debug(f"翻译结果数量和原文数量不一致: {len(translated_parts)} != {len(strings_to_translate)}")
            return

        # 更新文件内容
        
        translated_index = 0
        mark = 0

        for iner, line in enumerate(content):
            if  iner < lastnum :
                continue
            if iner > linenum :
                break
            # 处理字符串常量
            # 假设 strings_to_translate 是字典，跳过前 n 个元素
            # n = 3  # 跳过前 3 个元素

            # 获取字典的所有键，并跳过前 n 个键
            keys_to_process = list(strings_to_translate.keys())[mark:]

    # 从指定的开始位置循环
            for index in keys_to_process:
                s = strings_to_translate[index]
                if s in line:
                    line = line.replace(s, f'{translated_parts[str(translated_index)]}',1)
                    translated_index += 1
                    mark += 1
                else:
                    break
        
            new_content.append(line)
            

    def translate_directory(self, directory):
        """
        遍历目录，递归处理所有.py文件
        每隔2秒发送一个请求
        """
        for root, _, files in os.walk(directory):
            for file in files:
                if file.endswith('.css') or file.endswith('.js') :
                # if file.endswith('.json') or file.endswith('.py') :
                # if file.endswith('.html') :
                # if file.endswith('.env') :
                    # or file.endswith('.py') 
                    file_path = os.path.join(root, file)
                    # print(f"处理文件: {file_path}")
                    self.process_file(file_path)
                    # 每处理一个文件后，等待2秒再处理下一个文件
                    time.sleep(0.02)

# 示例：递归翻译当前目录
if __name__ == "__main__":
    translator = Translate(id ="your id"  ,secret =  "your secret",source = 'ko',target = 'zh')
    directory_to_translate = "your dir"  # 你可以修改为你想翻译的目录
    translator.translate_directory(directory_to_translate)